import {
  loginByPhone,
  loginByEmail,
  refreshToken,
  userinfoDetail,
  getConfig,
} from "@/api/user";
import { getProtocolType } from "@/api/article";
import {
  getToken,
  setToken,
  getTokenTime,
  setTokenTime,
  removeToken,
  removeTokenTime,
  setRefreshToken,
  removeRefreshToken,
  getRefreshToken,
} from "@/utils/auth";
import websocketTool from "@/components/websocket/websocketTool";
const tokenv = getToken();
const tokent = getTokenTime();
let userInfo = localStorage.getItem("user_info");
if (userInfo !== "null") {
  userInfo = JSON.parse(userInfo);
}
let online_states = localStorage.getItem("online");
if (online_states !== "null") {
  online_states = JSON.parse(JSON.stringify(online_states));
}
const state = {
  tab: null,
  accountReg: null,
  timer: null,
  token: tokenv,
  tokenTime: tokent,
  userInfo: userInfo,
  securityInfo: null, // 安全状态信息
  local: "en",
  localary: [],
  changeLocal: 0,
  localDetail: "", //用来帮助，资讯，公告详情里面判断切换语言
  theme: "dark",
  levertradingtab: 2, //合约交易对展示 默认usdt
  stocktradingtab: 2, //股票投资交易对展示，默认美股
  stockLevertradingtab: 2,
  stockSecondtradingtab: 2,
  secondtradingtab: 2, //秒合约交易对展示 默认usdt
  dealtradingtab: 2, //币币交易对展示 默认usdt
  safety_verification_key: null, // 安全验证key
  coinComfirm: true, // true开启币币交易二次弹窗
  levelComfirm: true, // true开启合约交易二次弹出
  certificateType: null,
  online: online_states, //在线状态
  systemInfo: null,
  protocol: null,
  virtual_wallet: null,
  fastExchange: true, //闪兑显示状态
  activeParam: {
    activation_time: 0, //激活时间
    id: 0, //内容id
    showStatus: false, //是否弹出过
  }, //首页弹窗参数
  levelPage: "level", //页面头部合约交易或秒合约交易显示
  nftPage: "NFT", //页面头部NFT或元宇宙交易显示
  contractActive: null, //个人中心合约管理的侧边栏二级菜单
  stockActive: null, //个人中心股票管理的侧边栏二级菜单
  klStudies: [], //k线指标
  foreignKlStudies: [], //外汇k线指标
  stockKlStudies: [], //股票k线指标
};
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_CONTRACTACTION: (state, contractActive) => {
    state.contractActive = contractActive;
  },
  SET_STOCKACTION: (state, stockActive) => {
    state.stockActive = stockActive;
  },
  SET_LEVER_PAGE: (state, levelPage) => {
    state.levelPage = levelPage;
  },
  SET_NFT_PAGE: (state, nftPage) => {
    state.nftPage = nftPage;
  },
  SET_TIMER: (state, timer) => {
    state.timer = timer;
  },
  SET_TAB: (state, tab) => {
    state.tab = tab;
  },
  SET_ACCOUNTREG: (state, accountReg) => {
    state.accountReg = accountReg;
  },
  SET_TOKEN_TIME: (state, tokenTime) => {
    state.tokenTime = tokenTime;
  },
  SET_LOCAL: (state, local) => {
    state.local = local;
  },
  SET_LOCALARY: (state, localary) => {
    state.localary = localary;
  },
  SET_LOCAL_DETAIL: (state, localDetail) => {
    state.localDetail = localDetail;
  },
  SET_CHANGELOCAL: (state, changeLocal) => {
    state.changeLocal = changeLocal;
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo;
  },
  SET_THEME: (state, theme) => {
    console.log(theme);
    state.theme = theme;
  },
  SET_SECURITY_INFO: (state, securityInfo) => {
    state.securityInfo = securityInfo;
  },
  SET_SAFETY_KEY: (state, safety_verification_key) => {
    state.safety_verification_key = safety_verification_key;
  },
  SET_COIN_COMFIRM: (state, coinComfirm) => {
    state.coinComfirm = coinComfirm;
  },
  SET_LEVER_COMFIRM: (state, levelComfirm) => {
    state.levelComfirm = levelComfirm;
  },
  SET_CERTIFICATE_TYPE: (state, certificateType) => {
    state.certificateType = certificateType;
  },
  SET_TRADING_TAB: (state, param) => {
    if (param.type === "lever") {
      state.levertradingtab = param.active;
    } else if (param.type === "stock") {
      state.stocktradingtab = param.active;
    } else if (param.type === "stockLever") {
      state.stockLevertradingtab = param.active;
    } else if (param.type === "stockSecond") {
      state.stockSecondtradingtab = param.active;
    } else {
      state.dealtradingtab = param.active;
    }
  },
  SET_TRADING_TAB_SEC: (state, param) => {
    state.secondtradingtab = param.active;
  },
  SET_ONLINE: (state, online) => {
    state.online = online;
  },
  SET_SYSTEMINFO: (state, systemInfo) => {
    state.systemInfo = systemInfo;
  },
  SET_PROTOCOL: (state, protocol) => {
    state.protocol = protocol;
  },
  SET_FASTEXCHANGE: (state, fastExchange) => {
    state.fastExchange = fastExchange;
  },
  SET_ACTIVEPARAM: (state, activeParam) => {
    state.activeParam = activeParam;
  },
  SET_KLSTUDIES: (state, klStudies) => {
    state.klStudies = klStudies;
  },
  SET_STOCKKLSTUDIES: (state, stockKlStudies) => {
    state.stockKlStudies = stockKlStudies;
  },
  SET_FOREIGN_KLSTUDIES: (state, foreignKlStudies) => {
    state.foreignKlStudies = foreignKlStudies;
  },
  SET_VIRTUAL_WALLET: (state, virtual_wallet) => {
    state.virtual_wallet = virtual_wallet;
  },
};

const offLine = () => {
  let user = localStorage.getItem("user_info");
  if (user !== null) {
    user = JSON.parse(user);
  }
  localStorage.removeItem("online");
  if (websocketTool?.ws && websocketTool?.ws?.readyState == 1) {
    if (user) {
      websocketTool?.ws.send(
        JSON.stringify({
          socket_type: `OFFLINE_${user.id}`,
          subscribed: 1,
        })
      );
    }
  }
};

const actions = {
  // user login
  login({ commit }, params) {
    console.log(params);
    const requestFun = params.loginType === 1 ? loginByPhone : loginByEmail;
    return new Promise((resolve, reject) => {
      requestFun(params)
        .then((response) => {
          console.log(response,'res')
          if (response.code === 1) {
            console.log(response);
            const data = response.data;
            const timestamp = Date.parse(new Date()) / 1000;
            // console.log(timestamp, data.access_token_valid_time);
            commit("SET_TOKEN_TIME", 604800 - 50);
            console.log("state", state, data.token);
            commit("SET_TOKEN", data.token);
            setToken(data.token);
            setTokenTime(604800 - 50);
            setRefreshToken(2592000);
            let user_info = data;
            if (params.login_type === 1) {
              localStorage.setItem("phone", user_info.mobile);
            } else {
              localStorage.setItem("email", user_info.email);
            }
            userinfoDetail().then(res=>{
              commit("SET_USER_INFO", res.data);
              commit("SET_ONLINE", "online");
              localStorage.setItem("online", "online");
              localStorage.setItem("user_info", JSON.stringify(res.data));
            })
    
            this.dispatch("user/changeSecurity");
            resolve();
          } else {
            console.log(response.msg)
            reject(response.msg);
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  // user logout
  logout({ commit }) {
    return new Promise((resolve) => {
      offLine();
      commit("SET_TOKEN", "");
      commit("SET_TOKEN_TIME", "");
      removeToken();
      removeTokenTime();
      removeRefreshToken();
      commit("SET_USER_INFO", null);
      commit("SET_SECURITY_INFO", null);
      commit("SET_VIRTUAL_WALLET", null);
      localStorage.removeItem("user_info");
      resolve();
    });
  },
  removeToken({ commit }) {
    commit("SET_TOKEN", "");
  },
  // remove token
  resetToken({ commit }) {
    const refreshtoken = getRefreshToken();
    return new Promise((resolve, reject) => {
      if (refreshtoken) {
        refreshToken(refreshtoken)
          .then((response) => {
            if (response.code === 200) {
              const data = response.data;
              // const timestamp = Date.parse(new Date()) / 1000
              let time = 604800 - 50;
              commit("SET_TOKEN", data.token);
              commit("SET_TOKEN_TIME", time);
              setToken(data.token);
              setTokenTime(time);
              setRefreshToken(2592000);
              let user_info = data;
              commit("SET_ONLINE", "online");
              localStorage.setItem("online", "online");
              commit("SET_USER_INFO", user_info);
              localStorage.setItem("user_info", JSON.stringify(user_info));
              this.dispatch("user/changeSecurity");
              resolve();
            } else {
              commit("SET_TOKEN", "");
              commit("SET_TOKEN_TIME", "");
              removeToken();
              removeTokenTime();
              removeRefreshToken();
              reject();
            }
          })
          .catch((error) => {
            reject(error);
          });
      } else {
        commit("SET_TOKEN", "");
        commit("SET_TOKEN_TIME", "");
        removeToken();
        removeTokenTime();
        removeRefreshToken();
        reject();
      }
    });
  },
  // 修改模拟账号状态
  changeVirtualWallet({ commit }, params) {
    return new Promise((resolve) => {
      console.log(params);
      commit("SET_VIRTUAL_WALLET", params);
      resolve();
    });
  },
  // 修改语言
  changeLocal({ commit }, params) {
    return new Promise((resolve) => {
      console.log(params);
      commit("SET_LOCAL", params);
      commit("SET_CHANGELOCAL", 1);
      resolve();
    });
  },
  // 修改主题
  changeTheme({ commit }, params) {
    return new Promise((resolve) => {
      commit("SET_THEME", params);
      resolve();
    });
  },
  //获取协议配置信息
  getProtocolConfig({ commit }) {
    return new Promise((resolve, reject) => {
      getProtocolType()
        .then((response) => {
          if (response.code === 200) {
            const data = response.data;
            commit("SET_PROTOCOL", data);
            resolve();
          } else {
            reject(response.message);
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  //获取系统配置信息
  changeSystemConfig({ commit }) {
    return new Promise((resolve, reject) => {
      getConfig()
        .then((response) => {
          if (response.code === 1) {
            const data = response.data;
            let datas=[  {
              "key": "invitation_code_status",
              "notes": "邀请码是否必填(true-是，false-否)",
              "value": false
          },
          {
              "key": "template_pc",
              "notes": "PC模板",
              "value": "1"
          },
          {
              "key": "template_app",
              "notes": "APP模板",
              "value": "1"
          },
          {
              "key": "wallet_transaction",
              "notes": "币币钱包是否展示(true-是，false-否)",
              "value": true
          },
          {
              "key": "wallet_legal",
              "notes": "法币钱包是否展示(true-是，false-否)",
              "value": true
          },
          {
              "key": "wallet_lever",
              "notes": "合约钱包是否展示(true-是，false-否)",
              "value": true
          },
          {
              "key": "wallet_second_lever",
              "notes": "秒合约钱包是否展示(true-是，false-否)",
              "value": true
          },
          {
              "key": "wallet_project",
              "notes": "理财钱包是否展示(true-是，false-否)",
              "value": true
          },
          {
              "key": "wallet_stock_second_lever",
              "notes": "股票秒合约钱包是否展示(true-是，false-否)",
              "value": true
          },
          {
              "key": "wallet_stock_lever",
              "notes": "股票合约钱包是否展示(true-是，false-否)",
              "value": true
          },
          {
              "key": "wallet_stock",
              "notes": "股票现货钱包是否展示(true-是，false-否)",
              "value": true
          },
          {
              "key": "easy_buy",
              "notes": "快捷买币(true-显示，false-隐藏)",
              "value": true
          },
          {
              "key": "easy_buy_type",
              "notes": "快捷买币跳转类型(1-链接，2-客服，3-法币页，4-三方联系)",
              "value": 1
          },
          {
              "key": "easy_buy_url",
              "notes": "跳转url",
              "value": "https://direct.lc.chat/17284854/"
          },
          {
              "key": "defi_ore_status",
              "notes": "挖矿入口(true-展示，false-隐藏)",
              "value": false
          },
          {
              "key": "wealth_management_status",
              "notes": "理财入口(true-展示，false-隐藏)",
              "value": true
          },
          {
              "key": "stock_status",
              "notes": "股票投资入口(true-展示，false-隐藏)",
              "value": true
          },
          {
              "key": "follow_status",
              "notes": "跟单入口(true-展示，false-隐藏)",
              "value": false
          },
          {
              "key": "defi_ore_logo",
              "notes": "defi挖矿标识(none-无，hot，new)",
              "value": "new"
          },
          {
              "key": "wealth_management_logo",
              "notes": "理财宝标识(none-无，hot，new)",
              "value": "new"
          },
          {
              "key": "stock_status",
              "notes": "股票现货交易入口开关(true-开，false-关)",
              "value": true
          },
          {
              "key": "stock_lever_status",
              "notes": "股票合约开关(true-开，false-关)",
              "value": true
          },
          {
              "key": "stock_second_lever_status",
              "notes": "股票秒合约开关(true-开，false-关)",
              "value": true
          },
          {
              "key": "fiat_currency_transaction_status",
              "notes": "法币交易开关(true-开，false-关)",
              "value": true
          },
          {
              "key": "currency_transaction_status",
              "notes": "币币交易开关(true-开，false-关)",
              "value": true
          },
          {
              "key": "lever_status",
              "notes": "合约开关(true-开，false-关)",
              "value": true
          },
          {
              "key": "second_lever_status",
              "notes": "秒合约开关(true-开，false-关)",
              "value": true
          },
          {
              "key": "about_us_pc",
              "notes": "pc关于我们模板配置（1-默认模板，2-自定义）",
              "value": 1
          },
          {
              "key": "about_us_npc",
              "notes": "APP/H5关于我们模板配置（1-默认模板，2-自定义）",
              "value": 1
          },
          {
              "key": "about_us_pc_custom",
              "notes": "pc关于我们自定义内容",
              "value": ""
          },
          {
              "key": "about_us_npc_custom",
              "notes": "APP/H5关于我们自定义内容",
              "value": ""
          },
          {
              "key": "verify_switch",
              "notes": "实名认证开关（1-币币交易，2-合约交易，3-秒合约，4-理财，5-法币交易，6-提现，7-挖矿，8-股票現貨，9-股票合約，10-股票期權，11-外汇）",
              "value": [
                  false,
                  false,
                  false,
                  false,
                  false,
                  false,
                  false,
                  false,
                  false,
                  false,
                  false
              ]
          },
          {
              "key": "default_language_tag",
              "notes": "默认语言标识",
              "value": "zh"
          },
          {
              "key": "service_url",
              "notes": "客服跳转配置：online-在线客服页(Z)；contact-社交客服页；Monline-在线客服页(M)",
              "value": "online"
          },
          {
              "key": "maintenance_status",
              "notes": "维护状态",
              "value": false
          },
          {
              "key": "cancel_withdraw_status",
              "notes": "用户提现撤销状态设置（true-开启，false-关闭）",
              "value": true
          },
          {
              "key": "uid_status",
              "notes": "uid显示开关（true-开启，false-关闭）",
              "value": false
          },
          {
              "key": "metaverse_status",
              "notes": "元宇宙分类开关（true-开启，false-关闭）",
              "value": false
          },
          {
              "key": "nft_status",
              "notes": "NFT分类开关（true-开启，false-关闭）",
              "value": false
          },
          {
              "key": "default_phone_area_code",
              "notes": "默认注册国家code",
              "value": "USA"
          },
          {
              "key": "currency_subscription_status",
              "notes": "新币申购开关状态(true-开，false-关)",
              "value": false
          },
          {
              "key": "currency_subscription_logo",
              "notes": "新币申购标识(none-无，hot，new)",
              "value": "none"
          },
          {
              "key": "wallet_nft",
              "notes": "nft账户(true-显示，false-隐藏)",
              "value": false
          },
          {
              "key": "nft_entrance",
              "notes": "nft入口(true-显示，false-隐藏)",
              "value": false
          },
          {
              "key": "world_cup",
              "notes": "世界杯竞猜入口(true-显示，false-隐藏)",
              "value": false
          },
          {
              "key": "wealth_management_type",
              "notes": "理财和机器人托管切换(1-理财，2-机器人托管)",
              "value": 1
          },
          {
              "key": "withdraw_platform_user",
              "notes": "提现平台用户(true-开启，false-关闭)",
              "value": false
          },
          {
              "key": "meta_switch",
              "notes": "元宇宙入口(true-显示，false-隐藏)",
              "value": false
          },
          {
              "key": "wallet_status",
              "notes": "上链开关(true-开启，false-关闭)",
              "value": true
          },
          {
              "key": "recharge_manual",
              "notes": "充值提交(true-开启，false-关闭)",
              "value": true
          },
          {
              "key": "recharge_manual_amount",
              "notes": "转账数量(true-开启，false-关闭)",
              "value": true
          },
          {
              "key": "recharge_manual_hash",
              "notes": "hash地址/发送地址(true-开启，false-关闭)",
              "value": false
          },
          {
              "key": "recharge_manual_transaction",
              "notes": "转账截图(true-开启，false-关闭)",
              "value": true
          },
          {
              "key": "stock_subscription_status",
              "notes": "新股申购开关状态(true-开，false-关)",
              "value": false
          },
          {
              "key": "stock_subscription_logo",
              "notes": "新股申购标识(none-无，hot，new)",
              "value": "none"
          },
          {
              "key": "platform_cover_image",
              "notes": "平台封面图",
              "value": ""
          },
          {
              "key": "platform_video_link",
              "notes": "平台视频简介",
              "value": ""
          },
          {
              "key": "foreign_exchange",
              "notes": "外汇入口(true-开，false-关)",
              "value": false
          },
          {
              "key": "wallet_forex",
              "notes": "外汇钱包(true-显示，false-隐藏)",
              "value": true
          },
          {
              "key": "default_wallet",
              "notes": "默认钱包(0-无，1-币币，2-法币，3-股票现货)",
              "value": 1
          },
          {
              "key": "remember_password",
              "notes": "记住密码(true-开启，false-关闭)",
              "value": false
          },
          {
              "key": "holding_id_card",
              "notes": "手持照片(认证)(true-开启，false-关闭)",
              "value": false
          },
          {
              "key": "platform_content_management",
              "notes": "平台内容开启[帮助中心,公告中心,资讯中心](true-开启，false-关闭)",
              "value": [
                  false,
                  false,
                  false
              ]
          },
          {
              "key": "pledge_borrowing_status",
              "notes": "质押借币开关(true-开启，false-关闭)",
              "value": false
          },
          {
              "key": "virtual_wallet",
              "notes": "虚拟账户(true-开启，false-关闭)",
              "value": false
          },
          {
              "key": "credit_score_status",
              "notes": "信誉分开关(true-开启，false-关闭)",
              "value": true
          },
          {
              "key": "stock_closed_operation",
              "notes": "未开市是否可平仓(true-是,false-否)",
              "value": false
          }];
            commit("SET_SYSTEMINFO", datas);
            resolve();
          } else {
            reject(response.message);
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  // 获取安全中心状态信息
  changeSecurity({ commit }) {
    return new Promise((resolve, reject) => {
      userinfoDetail()
        .then((response) => {
          if (response.code === 1) {
            const data = response.data;
            commit("SET_SECURITY_INFO", data);
            //更新一下用户信息
            console.log('更新一下用信息')
            commit("SET_USER_INFO", data);
            resolve();
          } else {
            reject(response.message);
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  // 修改安全验证key
  changeSafetyKey({ commit }, params) {
    return new Promise((resolve) => {
      commit("SET_SAFETY_KEY", params);
      resolve();
    });
  },
  // 修改币币交易二次确认弹窗
  changeCoinComfirm({ commit }, params) {
    return new Promise((resolve) => {
      commit("SET_COIN_COMFIRM", params);
      resolve();
    });
  },
  // 修改合约交易二次确认弹窗
  changeLevelComfirm({ commit }, params) {
    return new Promise((resolve) => {
      commit("SET_LEVER_COMFIRM", params);
      resolve();
    });
  },
  changeCertificateType({ commit }, params) {
    return new Promise((resolve) => {
      commit("SET_CERTIFICATE_TYPE", params);
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
